<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>K线图</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow-x: hidden;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 10px;
            box-sizing: border-box;
        }
        #kline-chart {
            width: 100%;
            height: 70vh;
            min-height: 400px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .controls {
            margin: 10px 0;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
        }
        select {
            margin: 5px;
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #fff;
            font-size: 14px;
        }
        .error {
            color: #e53935;
            margin: 10px;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            display: none;
        }
        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                align-items: flex-start;
            }
            select {
                width: 100%;
                margin: 5px 0;
            }
            #kline-chart {
                height: 60vh;
            }
        }
        .loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #666;
            font-size: 14px;
            background: rgba(255,255,255,0.8);
            padding: 10px 20px;
            border-radius: 4px;
            z-index: 10;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="controls">
            <div>
                <select id="symbol">
                    <option value="BTCUSDT">BTCUSDT</option>
                    <option value="ETHUSDT">ETHUSDT</option>
                    <option value="SOLUSDT">SOLUSDT</option>
                    <option value="BNBUSDT">BNBUSDT</option>
                </select>
                <select id="interval">
                    <option value="10m">10分钟</option>
                    <option value="15m">15分钟</option>
                    <option value="30m">30分钟</option>
                    <option value="1h">1小时</option>
                    <option value="1d">1天</option>
                </select>
            </div>
            <div id="error" class="error"></div>
        </div>
        <div id="kline-chart-container" style="position: relative;">
            <div id="loading" class="loading" style="display: none;">加载数据中...</div>
            <div id="kline-chart"></div>
        </div>
    </div>

    <script>
        var myChart = null;
        
        // 获取今天的开始时间（0点）
        function getTodayStartTime() {
            const now = new Date();
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            return today.getTime();
        }
        
        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            setTimeout(() => {
                errorDiv.style.display = 'none';
            }, 3000);
        }
        
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
        }
        
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }
        
        function initChart() {
            const chartContainer = document.getElementById('kline-chart');
            if (!chartContainer) {
                console.error('找不到K线图容器元素');
                return false;
            }
            
            if (!myChart) {
                try {
                    myChart = echarts.init(chartContainer);
                    console.log('K线图初始化成功');
                } catch (error) {
                    console.error('初始化K线图失败:', error);
                    return false;
                }
            }
            
            return true;
        }
        
        function loadKlineData() {
            const symbol = document.getElementById('symbol').value;
            const interval = document.getElementById('interval').value;
            
            const startTime = getTodayStartTime();
            const endTime = Date.now();
            
            // 显示加载动画
            showLoading();
            
            if (!initChart()) {
                hideLoading();
                showError('无法初始化图表');
                return;
            }
            
            myChart.showLoading();
            
            const params = new URLSearchParams({
                symbol,
                interval,
                startTime,
                endTime
            });
            
            fetch(`/api/klines?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    if (data.length === 0) {
                        showError('未找到数据');
                        return;
                    }
                    
                    const klineData = data.map(item => [
                        parseInt(item[0]), // 时间戳
                        parseFloat(item[1]), // 开盘价
                        parseFloat(item[2]), // 最高价
                        parseFloat(item[3]), // 最低价
                        parseFloat(item[4])  // 收盘价
                    ]);
                    
                    // 计算数据的时间范围
                    const times = klineData.map(item => item[0]);
                    const minTime = Math.min(...times);
                    const maxTime = Math.max(...times);
                    
                    // 配置K线图
                    const option = {
                        title: {
                            text: `${symbol} ${interval} K线图`,
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'cross'
                            },
                            formatter: function (params) {
                                const data = params[0].data;
                                return [
                                    '时间: ' + new Date(data[0]).toLocaleString(),
                                    '开盘: ' + data[1],
                                    '最高: ' + data[2],
                                    '最低: ' + data[3],
                                    '收盘: ' + data[4]
                                ].join('<br/>');
                            }
                        },
                        grid: {
                            left: '10%',
                            right: '10%',
                            bottom: '15%',
                            top: '60'
                        },
                        xAxis: {
                            type: 'time',
                            min: minTime,
                            max: maxTime,
                            axisLabel: {
                                formatter: function (value) {
                                    const date = new Date(value);
                                    return date.getMonth() + 1 + '/' + date.getDate() + ' ' + 
                                           date.getHours().toString().padStart(2, '0') + ':' + 
                                           date.getMinutes().toString().padStart(2, '0');
                                }
                            }
                        },
                        yAxis: {
                            type: 'value',
                            scale: true,
                            splitArea: {
                                show: true
                            }
                        },
                        dataZoom: [
                            {
                                type: 'inside',
                                start: 0,
                                end: 100
                            },
                            {
                                show: true,
                                type: 'slider',
                                bottom: '5%',
                                start: 0,
                                end: 100
                            }
                        ],
                        series: [
                            {
                                name: 'K线',
                                type: 'candlestick',
                                data: klineData,
                                itemStyle: {
                                    color: '#ef232a',
                                    color0: '#14b143',
                                    borderColor: '#ef232a',
                                    borderColor0: '#14b143'
                                }
                            }
                        ]
                    };
                    
                    // 使用配置项显示图表
                    myChart.setOption(option, true);
                    
                    // 确保调整大小
                    setTimeout(function() {
                        myChart.resize();
                    }, 100);
                })
                .catch(error => {
                    console.error('加载K线数据失败:', error);
                    showError(error.message || '加载数据失败，请重试');
                })
                .finally(() => {
                    myChart.hideLoading();
                    hideLoading();
                });
        }
        
        // 监听控件变化
        document.getElementById('symbol').addEventListener('change', loadKlineData);
        document.getElementById('interval').addEventListener('change', loadKlineData);
        
        // 页面加载完成后加载数据
        window.onload = function() {
            loadKlineData();
        };
        
        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            if (myChart) {
                myChart.resize();
            }
        });
    </script>
</body>
</html> 